﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Security.Principal;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;

namespace Coldairarrow.Business.Base_Manage
{
    public class OL_MoldBusiness
    {
        public IDbAccessor Db { get; set; }
        /// <summary>
        /// 钉钉流程表单操作业务
        /// </summary>
        public STK_MoldInterfaceBusiness _STK_MoldInterfaceBusiness { get; set; }

        public DD_ProcessInterfaceBusiness _DD_ProcessInterfaceBusiness { get; set; }
        public OL_MoldBusiness(IDbAccessor db)
        {
            this.Db = db;
            _STK_MoldInterfaceBusiness = new STK_MoldInterfaceBusiness();
            _DD_ProcessInterfaceBusiness = new DD_ProcessInterfaceBusiness();
        }

        /// <summary>
        /// 开模新增
        /// </summary>
        /// <param name="moldDTO"></param>
        /// <returns></returns>
        public async Task AddMolds(MoldDTO moldDTO)
        {
            if (!moldDTO.process_instance_id.IsNullOrEmpty() && !moldDTO.Mold_Item.IsNullOrEmpty())
            {
                if (moldDTO.Mold_Item.Count > 0)
                {
                    //获取钉钉表单信息
                    ProcessDTO process = await GetProcess(moldDTO);
                    //获取单据体信息
                    string DDBill = moldDTO.DDBillNo;//审批单号
                    string DDApDate = process.process_instance.create_time;//申请时间
                    List<Mold> newItems = new List<Mold>();//
                    List<Mold> editIems = new List<Mold>();
                    //判断模具编号是否有空的项
                    moldDTO.Mold_Item=moldDTO.Mold_Item.Where(x => !x.Number.IsNullOrEmpty() && !x.Qty.IsNullOrEmpty()).ToList();


                    if (!moldDTO.Mold_Item.IsNullOrEmpty())
                    {
                        moldDTO.Mold_Item.ForEach(item =>
                        {
                            //判断模具是改模还是开模，R开头的编号为改模
                            if (!item.Number.StartsWith("R"))
                            {
                                item.Number = item.Number.Trim();
                                item.DDAddBill = DDBill;
                                item.DDAddType = moldDTO.DDBillType;
                                item.DDAddDate = DDApDate;
                                item.State = "开模中";
                                newItems.Add(item);
                            }
                            else
                            {
                                //将开头的第一个R去掉为模具标号
                                item.Number = item.Number.Trim().Substring(2);
                                item.DDEditBill = DDBill;
                                item.DDEditType = moldDTO.DDBillType;
                                item.DDEditDate = DDApDate;
                                item.State = "改模中";
                                editIems.Add(item);
                            }
                        });
                    }
                    if (newItems.Count() > 0) await _STK_MoldInterfaceBusiness.AddRow(newItems);
                    if (editIems.Count() > 0) await EditMolds(editIems);
                }
            }
        }

        /// <summary>
        /// 改模修改
        /// </summary>
        /// <param name="newItems"></param>
        /// <returns></returns>
        public async Task EditMolds(List<Mold> newItems)
        {

            if (!newItems.IsNullOrEmpty() && newItems.Count > 0)
            {
                //获取需要更新的项
                List<OL_FilterDTO> filters = new List<OL_FilterDTO>();//过滤条件
                newItems.ForEach(x =>
                {
                    OL_FilterDTO filter = new OL_FilterDTO()
                    {
                        ControlId = "67185c1ca23bbf6d2b4ec3b0",
                        DataType = 2,
                        FilterType = 2,
                        Value = x.Number,
                        SpliceType = 2
                    };
                    filters.Add(filter);
                });
                List<Mold> editItems = await _STK_MoldInterfaceBusiness.QueryRow(filters);

                //改模的更新项
                newItems.ForEach(newItem =>
                {
                    editItems.ForEach(editItem =>
                    {
                        if (editItem.Number == newItem.Number)
                        {
                            editItem.DDEditBill = newItem.DDEditBill;
                            editItem.DDEditType = newItem.DDEditType;
                            editItem.DDEditDate = newItem.DDEditDate;
                            editItem.State = newItem.State;
                            editItem.OperateType = "改模";
                        }
                    });
                });
                await _STK_MoldInterfaceBusiness.EditRow(editItems);
            }
        }


        /// <summary>
        /// 模具调拨
        /// </summary>
        /// <param name="moldDTO"></param>
        /// <returns></returns>
        public async Task TransMolds(MoldDTO moldDTO)
        {
            if (!moldDTO.process_instance_id.IsNullOrEmpty() && !moldDTO.Mold_Item.IsNullOrEmpty())
            {
                if (moldDTO.Mold_Item.Count > 0)
                {
                    //获取需要更新的项
                    List<OL_FilterDTO> filters = new List<OL_FilterDTO>();//过滤条件
                    moldDTO.Mold_Item.ForEach(x =>
                    {
                        OL_FilterDTO filter = new OL_FilterDTO()
                        {
                            ControlId = "67185c1ca23bbf6d2b4ec3b0",
                            DataType = 2,
                            FilterType = 2,
                            Value = x.Number.Trim(),
                            SpliceType = 2
                        };
                        filters.Add(filter);
                    });
                    List<Mold> transItems = await _STK_MoldInterfaceBusiness.QueryRow(filters);

                    //获取钉钉表单信息
                    ProcessDTO process = await GetProcess(moldDTO);
                    string DDBill = moldDTO.DDBillNo;//审批单号
                    string DDApDate = process.process_instance.create_time;//申请时间
                    string transType = moldDTO.DDBillType;//调拨类型

                    moldDTO.Mold_Item.ForEach(newItem =>
                    {

                        foreach (var oldItem in transItems)
                        {
                            if (oldItem.Number == newItem.Number)
                            {
                                if (transType == "报废") oldItem.State = "报废";
                                oldItem.DDTransBill = DDBill;
                                oldItem.DDTransType = moldDTO.DDBillType;
                                oldItem.DDTransDate = DDApDate;
                                oldItem.Position_In = newItem.Position_In;
                                oldItem.Position_Out = newItem.Position_Out;
                                oldItem.OperateType = "调拨";
                                break;
                            }
                        }
                    });
                    await _STK_MoldInterfaceBusiness.EditRow(transItems);
                }
            }


        }

        /// <summary>
        /// 更新行
        /// </summary>
        /// <param name="moldDTO"></param>
        /// <returns></returns>
        public async Task EditRows(MoldDTO moldDTO)
        {

            if (moldDTO.Mold_Item.Count > 0)
            {
                //获取需要更新的项
                List<OL_FilterDTO> filters = new List<OL_FilterDTO>();//过滤条件
                moldDTO.Mold_Item.ForEach(x =>
                {
                    OL_FilterDTO filter = new OL_FilterDTO()
                    {
                        ControlId = "67185c1ca23bbf6d2b4ec3b0",
                        DataType = 2,
                        FilterType = 2,
                        Value = x.Number.Trim(),
                        SpliceType = 2
                    };
                    filters.Add(filter);
                });
                //获取旧的模具数据
                List<Mold> oldItems = await _STK_MoldInterfaceBusiness.QueryRow(filters);
                //需要更新的模具数据
                List<Mold> editItems = new List<Mold>();
                //循环替换需要更新的值
                moldDTO.Mold_Item.ForEach(newItem =>
                {
                    List<Mold> editMold = oldItems.Where(x => x.Number == newItem.Number).ToList();
                    if (editMold.Count > 0)
                    {

                        PropertyInfo[] properties = newItem.GetType().GetProperties();
                        foreach (PropertyInfo property in properties)
                        {
                            var v = newItem.GetPropertyValue(property.Name);
                            if (!v.IsNullOrEmpty())
                            {
                                if (moldDTO.Mold_Item.Contains(v))
                                {

                                }
                                editMold[0].SetPropertyValue(property.Name, v.ToString());

                            }
                        }

                    }
                    editItems.Add(editMold[0]);
                });
                await _STK_MoldInterfaceBusiness.EditRow(editItems);
            }
        }


        /// <summary>
        /// 获取钉钉流程单据信息
        /// </summary>
        /// <param name="moldDTO">查询的单据ID参数</param>
        /// <returns></returns>
        public async Task<ProcessDTO> GetProcess(MoldDTO moldDTO)
        {
            List<ProcessDTO> processDTOs = await _DD_ProcessInterfaceBusiness.QueryProcess(moldDTO);
            ProcessDTO processDTO = processDTOs[0];
            return processDTO;
        }

    }
}